package com.lcxw.hxzbapi.controller.giftandcubecontroller;

import com.alibaba.fastjson.JSONObject;
import com.lcxw.hxzbapi.controller.roomcontroller.RoomRealization;
import com.lcxw.hxzbapi.entity.pojo.Cube;
import com.lcxw.hxzbapi.entity.pojo.CubeResult;
import com.lcxw.hxzbapi.entity.pojo.YwpdGiftBag;
import com.lcxw.hxzbapi.entity.pojo.YwpdMember;
import com.lcxw.hxzbapi.service.CubeService;
import com.lcxw.hxzbapi.service.GiftBagService;
import com.lcxw.hxzbapi.service.YwpdMemberService;
import com.lcxw.hxzbcommon.common.RedisUtils;
import com.lcxw.hxzbcommon.common.RoomUtils;
import com.lcxw.hxzbcommon.common.StringUtil;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.C;
import org.springframework.stereotype.Component;

/**
 * 魔方的实现类
 */

@Component
@Slf4j
public class CubeRealization {

    @Resource
    CubeService cubeService;

    @Resource
    GiftRealization giftRealization;

    @Resource
    GiftBagService giftBagService;

    @Resource
    RedisUtils redisUtils;

    @Resource
    RoomRealization roomRealization;

    public CubeResult luckyDraw(long userId, long roomId, String type) throws Exception {
        List<Cube> cubes = cubeService.selectByType(type);
        int cubesSize = cubes.size();

        //判断该房间是否在爆灯状态下，如果在爆灯状态下，则需要将极品的抽奖概率 翻3倍
        String baodeng_countDown_redisKey = RoomUtils.get_baodeng_countDown_redisKey(roomId);
        int baodengCountDown = 0;
        if (null != redisUtils.string_get(baodeng_countDown_redisKey)) {
            baodengCountDown = Integer.parseInt(redisUtils.string_get(baodeng_countDown_redisKey));
        }

        //如果爆灯剩余时间大于0，则将爆灯礼物的中奖率翻3倍
        if (baodengCountDown > 0) {
            for (int i = 0; i < cubesSize; i++) {
                if (1 == cubes.get(i).getIsBaodeng()) {
                    Cube cube = cubes.get(i);
                    cube.setOdds(cube.getOdds() * 3);
                    cubes.remove(cubes.get(i));
                    cubes.add(i, cube);
                }
            }
        }

        int prizeIndex = getPrizeIndex(cubes);
        Cube cube = cubes.get(prizeIndex);

        //更新背包里抽中的奖品数量
        updateGiftBag(userId, cube);

        //减去抽奖用户的抽奖次数
        giftRealization.minusTicket(userId, type, 1);

        int baodengValue = roomRealization.setBaodengValue(roomId, 10);
        if (baodengValue >= 200) {
            roomRealization.initBaodeng(roomId);
            roomRealization.startBaodeng(roomId);
        }

        CubeResult cubeResult = new CubeResult();
        cubeResult.setPrizeIndex(prizeIndex);
        cubeResult.setNum(1);
        cubeResult.setCube(cube);

        log.info("用户 {} 抽中了一个{}", userId, cube.getGiftName());
        return cubeResult;
    }

    private void updateGiftBag(long userId, Cube cube) {
        int giftId = cube.getGiftId();
        if (null == giftBagService.selectByUserIdAndGiftId(userId, giftId)) {
            YwpdGiftBag ywpdGiftBag = new YwpdGiftBag();
            ywpdGiftBag.setGiftId(giftId);
            ywpdGiftBag.setGiftNum(1);
            ywpdGiftBag.setUserId(userId);
            ywpdGiftBag.setAddTime(StringUtil.getDateTime());
            giftBagService.insert(ywpdGiftBag);
        } else {
            giftBagService.updateGiftNum(userId, giftId, 1);
        }

    }

    public int getPrizeIndex(List<Cube> cubes) {
        int random = -1;
        try {
            //计算总权重
            double sumWeight = 0;
            for (Cube cube : cubes) {
                sumWeight += cube.getOdds();
            }

            //产生随机数
            double randomNumber;
            randomNumber = Math.random();

            //根据随机数在所有奖品分布的区域并确定所抽奖品
            double d1 = 0;
            double d2 = 0;
            for (int i = 0; i < cubes.size(); i++) {
                d2 += Double.parseDouble(String.valueOf(cubes.get(i).getOdds())) / sumWeight;
                if (i == 0) {
                    d1 = 0;
                } else {
                    d1 +=
                        Double.parseDouble(String.valueOf(cubes.get(i - 1).getOdds())) / sumWeight;
                }
                if (randomNumber >= d1 && randomNumber <= d2) {
                    random = i;
                    break;
                }
            }
        } catch (Exception e) {
            log.error("生成抽奖随机数出错，出错原因：{}", e.getMessage());
        }
        return random;
    }
}
